package com.goldplusgold.tradedelay.app.market.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.goldplusgold.support.lib.utils.StringConvertNumber;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.market.MarketManager;
import com.goldplusgold.tradedelay.app.market.eventbus.MessageEvent;
import com.goldplusgold.tradedelay.app.market.pojo.StickData;
import com.goldplusgold.tradedelay.app.market.widget.chartutil.ColorUtil;
import com.goldplusgold.tradedelay.app.market.widget.chartutil.IndexParseUtil;
import com.goldplusgold.tradedelay.app.market.widget.chartview.CrossView;
import com.goldplusgold.tradedelay.app.market.widget.chartview.KLineView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * Created by Arvin on 2016/10/25.
 */
public class KLineFragment extends LineBaseFragment implements KLineView.OnCrossListener {

    public static final int KLINE_REQUEST_CODE = 100175;//k线请求的code
    @BindView(R.id.k_cff_msg)
    TextView msgText;
    @BindView(R.id.ckf_klineview)
    KLineView mKLineView;
    @BindView(R.id.k_cff_cross)
    CrossView crossView;

    private List<StickData> dataList = new ArrayList<>();
    private Market.Category mCategory;
    private Market.InstType mInstType;

    @Nullable
    public static KLineFragment newInstance(Market.InstType instType, Market.Category category) {
        Bundle args = new Bundle();
        args.putSerializable("mInstType", instType);
        args.putSerializable("type", category);
        KLineFragment fragment = new KLineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null && !args.isEmpty()) {
            mInstType = (Market.InstType) args.getSerializable("mInstType");
            mCategory = (Market.Category) args.getSerializable("type");
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_kchart;
    }

    @Override
    public void initView() {
        mKLineView.setUsedViews(crossView, msgText);
        mKLineView.setType(1);
        mKLineView.setOnDoubleTapListener(this);
        mKLineView.setOnCrossListener(this);
    }


    public void changeType(Market.InstType instType){
        if(this.mInstType == instType){
            return;
        }
        this.mInstType = instType;
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        switch (tab.getPosition()) {
//            case INDEX_VOL:
//                mKLineView.showVOL();
//                break;
//            case INDEX_ZJ:
//                mKLineView.showZJ();
//                break;
//            case INDEX_MACD:
//                mKLineView.showMACD();
//                break;
//            case INDEX_KDJ:
//                mKLineView.showKDJ();
//                break;
        }
    }

    public void refreshPage(String title) {
        switch (title) {
            case "1分":
                mCategory = Market.Category.KLINEMIN1PAGE;
                break;
            case "5分":
                mCategory = Market.Category.KLINEMIN5PAGE;
                break;
            case "15分":
                mCategory = Market.Category.KLINEMIN15PAGE;
                break;
            case "30分":
                mCategory = Market.Category.KLINEMIN30PAGE;
                break;
            case "60分":
                mCategory = Market.Category.KLINEMIN60PAGE;
                break;
            case "240分":
                mCategory = Market.Category.KLINEMIN240PAGE;
                break;
        }
        MarketManager.getInstance().sendRequestMsg(mInstType, mCategory);
    }

    public void sendMinuteRequest(){
        MarketManager.getInstance().sendRequestMsg(mInstType, mCategory);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }


    @Override
    public void onDismiss() {
        Fragment f = getParentFragment();
        if (f != null && f instanceof QuotationChartFragment) {
            ((QuotationChartFragment) f).hideKLineTitle();
        }
    }

    @Override
    public void onShow(StickData data, StickData preData) {
        Fragment f = getParentFragment();
        if (f != null && f instanceof QuotationChartFragment) {
            ((QuotationChartFragment) f).showKLineTitle(data, preData);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onKLineEventBus(MessageEvent event) {
        if (event.getType() == mCategory && event.getIdentification().getInstType() == mInstType) {
            if(this.isVisible()){
                KLineViewBindWithStickData(event.getQuoteKline());
            }
        }
    }

    @SuppressWarnings("unchecked")
    public void  KLineViewBindWithStickData(Market.QuoteKline quoteKline) {
        if (quoteKline == null) {
            return;
        }
        int size = quoteKline.getAmountList().size();
        StickData stickData;
        if(size == 1){
            int i = 0;
            int id = (int) quoteKline.getId(i);
            double high = StringConvertNumber.parseDouble(quoteKline.getHigh(i));
            double low = StringConvertNumber.parseDouble(quoteKline.getLow(i));
            long volume = quoteKline.getVolume(i);
            double k_max = 0;
            double k_min = Double.MAX_VALUE;
            double c_max = 0;
            stickData = new StickData();
            stickData.setId(id);
            stickData.setTime(StringConvertNumber.parseInt(String.valueOf(quoteKline.getId(i)).substring(0, String.valueOf(quoteKline.getId(i)).length() - 3)));
            stickData.setDate(quoteKline.getTime(i));
            stickData.setOpen(StringConvertNumber.parseDouble(quoteKline.getOpen(i)));
            stickData.setClose(StringConvertNumber.parseDouble(quoteKline.getClose(i)));
            stickData.setHigh(high);
            stickData.setLow(low);
            stickData.setMoney(StringConvertNumber.parseDouble(quoteKline.getAmount(i)));
            stickData.setCount(quoteKline.getVolume(i));
            int count = dataList.size();
            if(dataList.get(count -1).getId() == id){
                dataList.remove(count - 1);
            }
            dataList.add(stickData);
            count = dataList.size();
            int to_index = count;
            //量的SMA5
            double csma5 = IndexParseUtil.getCountSma(dataList.subList(to_index -IndexParseUtil.START_SMA5 -1, to_index));
            double sma5 = IndexParseUtil.getCloseSma(dataList.subList(to_index -IndexParseUtil.START_SMA5 -1, to_index));
            double csma10 = IndexParseUtil.getCountSma(dataList.subList(to_index - IndexParseUtil.START_SMA10 - 1, to_index));
            double sma10 = IndexParseUtil.getCloseSma(dataList.subList(to_index - IndexParseUtil.START_SMA10 -1, to_index));
            double csma20 = IndexParseUtil.getCountSma(dataList.subList(to_index - IndexParseUtil.START_SMA20 -1, to_index ));
            double sma20 = IndexParseUtil.getCloseSma(dataList.subList(to_index - IndexParseUtil.START_SMA20 -1, to_index ));
            dataList.get(count -1).setCountSma5(csma5);
            //K线的SMA5
            dataList.get(count -1).setSma5(sma5);
            //第10日开始计算10日均线
            //量的SMA10
            dataList.get(count -1).setCountSma10(csma10);
            //K线的SMA10
            dataList.get(count -1).setSma10(sma10);
            //K线的SMA20
            dataList.get(count -1).setCountSma20(csma20);
            dataList.get(count -1).setSma20(sma20);

            k_max = high > k_max? high:k_max;
            k_max = sma5 > k_max? sma5:k_max;
            k_max = sma10 > k_max? sma10:k_max;
            k_max = sma20 > k_max? sma20:k_max;
            k_min = low < k_min?low:k_min;
            k_min = sma5 < k_min?sma5:k_min;
            k_min = sma10 < k_min?sma10:k_min;
            k_min = sma20 < k_min?sma20:k_min;
            dataList.get(count -1).setK_lineYmax(k_max);
            dataList.get(count -1).setK_lineYmin(k_min);
            c_max = volume > c_max? volume:c_max;
            c_max = csma5 > c_max? csma5:c_max;
            c_max = csma10 > c_max? csma10:c_max;
            c_max = csma20 > c_max? csma20:c_max;
            dataList.get(count -1).setC_lineYmax(c_max);
            refreshView(new ArrayList<StickData>(dataList));
        } else{
            if(size > 200){
                fastRefreshData(quoteKline);
            } else{
                handleData(quoteKline);
            }
        }
    }

    private void handleData(Market.QuoteKline quoteKline){
        if (quoteKline == null) {
            return;
        }
        int size = quoteKline.getAmountList().size();
        StickData stickData;
        dataList.clear();
        for (int i = 0; i < size; i++) {
            double k_max = 0;
            double k_min = Double.MAX_VALUE;
            double c_max = 0;
            int id = (int) quoteKline.getId(i);
            double high = StringConvertNumber.parseDouble(quoteKline.getHigh(i));
            double low = StringConvertNumber.parseDouble(quoteKline.getLow(i));
            long volume = quoteKline.getVolume(i);
            stickData = new StickData();
            stickData.setId(id);
            stickData.setTime(StringConvertNumber.parseInt(String.valueOf(quoteKline.getId(i)).substring(0, String.valueOf(quoteKline.getId(i)).length() - 3)));
            stickData.setDate(quoteKline.getTime(i));
            stickData.setOpen(StringConvertNumber.parseDouble(quoteKline.getOpen(i)));
            stickData.setClose(StringConvertNumber.parseDouble(quoteKline.getClose(i)));
            stickData.setHigh(StringConvertNumber.parseDouble(quoteKline.getHigh(i)));
            stickData.setLow(StringConvertNumber.parseDouble(quoteKline.getLow(i)));
            stickData.setMoney(StringConvertNumber.parseDouble(quoteKline.getAmount(i)));
            stickData.setCount(quoteKline.getVolume(i));
            dataList.add(stickData);
            int to_index = i+1;
            if(to_index >= size){
                to_index = size;
            }
            double csma5 = 0;
            double sma5 = 0;
            double csma10 = 0;
            double sma10 = 0;
            double csma20 = 0;
            double sma20 = 0;
            if ( i >= IndexParseUtil.START_SMA5 ) {
                csma5 = IndexParseUtil.getCountSma(dataList.subList(to_index -IndexParseUtil.START_SMA5 -1, to_index));
                sma5 = IndexParseUtil.getCloseSma(dataList.subList(to_index -IndexParseUtil.START_SMA5 -1, to_index));
                //量的SMA5
                dataList.get(i).setCountSma5(csma5);
                //K线的SMA5
                dataList.get(i).setSma5(sma5);
            }
            //第10日开始计算10日均线
            if (i >= IndexParseUtil.START_SMA10 ) {
                csma10 = IndexParseUtil.getCountSma(dataList.subList(to_index - IndexParseUtil.START_SMA10 - 1, to_index));
                sma10 = IndexParseUtil.getCloseSma(dataList.subList(to_index - IndexParseUtil.START_SMA10 -1, to_index));
                //量的SMA10
                dataList.get(i).setCountSma10(csma10);
                //K线的SMA10
                dataList.get(i).setSma10(sma10);
            }
            if (i >= IndexParseUtil.START_SMA20 ) {
                csma20 = IndexParseUtil.getCountSma(dataList.subList(to_index - IndexParseUtil.START_SMA20 -1, to_index ));
                sma20 = IndexParseUtil.getCloseSma(dataList.subList(to_index - IndexParseUtil.START_SMA20 -1, to_index ));
                //K线的SMA20
                dataList.get(i).setCountSma20(csma20);
                dataList.get(i).setSma20(sma20);
            }
            k_max = high > k_max? high:k_max;
            k_max = sma5 > k_max? sma5:k_max;
            k_max = sma10 > k_max? sma10:k_max;
            k_max = sma20 > k_max? sma20:k_max;
            k_min = low < k_min?low:k_min;
            if(sma5 != 0){
                k_min = sma5 < k_min?sma5:k_min;
            }
            if(sma10 != 0){
                k_min = sma10 < k_min?sma10:k_min;
            }
            if(sma20 != 0){
                k_min = sma20 < k_min?sma20:k_min;
            }
            dataList.get(i).setK_lineYmax(k_max);
            dataList.get(i).setK_lineYmin(k_min);
            c_max = volume > c_max? volume:c_max;
            c_max = csma5 > c_max? csma5:c_max;
            c_max = csma10 > c_max? csma10:c_max;
            c_max = csma20 > c_max? csma20:c_max;
            dataList.get(i).setC_lineYmax(c_max);
        }
        refreshView(new ArrayList<StickData>(dataList));
    }

    private void fastRefreshData(Market.QuoteKline quoteKline){
        if (quoteKline == null) {
            return;
        }
        List<StickData> datas = new ArrayList<>();
        int size = quoteKline.getAmountList().size();
        int start_index = size - 160;
        StickData stickData;
        int sma_index_sub = - 1 + start_index;
        int j = 0;
        for (int i = start_index; i < size; i++) {
            double k_max = 0;
            double k_min = Double.MAX_VALUE;
            double c_max = 0;
            double high = StringConvertNumber.parseDouble(quoteKline.getHigh(i));
            double low = StringConvertNumber.parseDouble(quoteKline.getLow(i));
            long volume = quoteKline.getVolume(i);
            int id = (int) quoteKline.getId(i);
            stickData = new StickData();
            stickData.setId(id);
            stickData.setTime(StringConvertNumber.parseInt(String.valueOf(quoteKline.getId(i)).substring(0, String.valueOf(quoteKline.getId(i)).length() - 3)));
            stickData.setDate(quoteKline.getTime(i));
            stickData.setOpen(StringConvertNumber.parseDouble(quoteKline.getOpen(i)));
            stickData.setClose(StringConvertNumber.parseDouble(quoteKline.getClose(i)));
            stickData.setHigh(StringConvertNumber.parseDouble(quoteKline.getHigh(i)));
            stickData.setLow(StringConvertNumber.parseDouble(quoteKline.getLow(i)));
            stickData.setMoney(StringConvertNumber.parseDouble(quoteKline.getAmount(i)));
            stickData.setCount(quoteKline.getVolume(i));
            datas.add(stickData);
            int to_index = j+1;
            if(to_index >= 160){
                to_index = 160;
            }
            double csma5 = 0;
            double sma5 = 0;
            double csma10 = 0;
            double sma10 = 0;
            double csma20 = 0;
            double sma20 = 0;
            if ( i >= IndexParseUtil.START_SMA5 + sma_index_sub) {

                csma5 = IndexParseUtil.getCountSma(datas.subList(to_index -IndexParseUtil.START_SMA5, to_index));
                sma5 = IndexParseUtil.getCloseSma(datas.subList(to_index -IndexParseUtil.START_SMA5, to_index));
                //量的SMA5
                datas.get(j).setCountSma5(csma5);
                //K线的SMA5
                datas.get(j).setSma5(sma5);
            }
            //第10日开始计算10日均线
            if (i >= IndexParseUtil.START_SMA10 + sma_index_sub) {

                csma10 = IndexParseUtil.getCountSma(datas.subList(to_index - IndexParseUtil.START_SMA10, to_index));
                sma10 = IndexParseUtil.getCloseSma(datas.subList(to_index - IndexParseUtil.START_SMA10, to_index));
                //量的SMA10
                datas.get(j).setCountSma10(csma10);
                //K线的SMA10
                datas.get(j).setSma10(sma10);
            }
            if (i >= IndexParseUtil.START_SMA20 + sma_index_sub) {
                csma20 = IndexParseUtil.getCountSma(datas.subList(to_index - IndexParseUtil.START_SMA20, to_index ));
                sma20 = IndexParseUtil.getCloseSma(datas.subList(to_index - IndexParseUtil.START_SMA20, to_index ));
                //K线的SMA20
                datas.get(j).setCountSma20(csma20);
                datas.get(j).setSma20(sma20);
            }
            k_max = high > k_max? high:k_max;
            k_max = sma5 > k_max? sma5:k_max;
            k_max = sma10 > k_max? sma10:k_max;
            k_max = sma20 > k_max? sma20:k_max;
            k_min = low < k_min?low:k_min;
            if(sma5 != 0){
                k_min = sma5 < k_min?sma5:k_min;
            }
            if(sma10 != 0){
                k_min = sma10 < k_min?sma10:k_min;
            }
            if(sma20 != 0){
                k_min = sma20 < k_min?sma20:k_min;
            }
            datas.get(j).setK_lineYmax(k_max);
            datas.get(j).setK_lineYmin(k_min);
            c_max = volume > c_max? volume:c_max;
            c_max = csma5 > c_max? csma5:c_max;
            c_max = csma10 > c_max? csma10:c_max;
            c_max = csma20 > c_max? csma20:c_max;
            datas.get(j).setC_lineYmax(c_max);
            j++;
        }
        refreshView(datas);
        handleData(quoteKline);
    }

    private void refreshView(final List<StickData> list){
        if (isAvailableActivity()) {
            this.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mKLineView == null) {
                        return;
                    }
                    mKLineView.setDataAndInvalidate(list, mInstType);
                    if (crossView != null && crossView.getVisibility() == View.GONE) {
                        msgText.setText(Html.fromHtml(ColorUtil.getCurPriceInfo((StickData) list.get(list.size() - 1), mInstType)));
                    }
                }
            });
        }
    }

}
